#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"

void HeapInit(Heap* php)
{
	assert(php);
	php->data = (HeapDataType*)malloc(sizeof(HeapDataType)*4);
	php->capacity = 4;
	php->size = 0;
}

void HeapDestroy(Heap* php)
{
	assert(php);
	free(php->data);
	php->capacity = php->size = 0;
}

void Swap(HeapDataType* p1, HeapDataType* p2)
{
	HeapDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustUp(HeapDataType* data, int child)
{
	assert(data);
	int parent = (child - 1) / 2;
	while(child > 0)
	{
		if (data[child] < data[parent])
		{
			Swap(&data[child], &data[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(Heap* php, HeapDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		HeapDataType* tmp = (HeapDataType*)realloc(php->data, sizeof(HeapDataType)*(php->capacity*2));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		php->data = tmp;
		php->capacity *= 2;
	}

	php->data[php->size] = x;
	php->size++;

	AdjustUp(php->data, php->size-1);

}

bool HeapEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}

void AdjustDown(HeapDataType* data, int n, int parent)
{
	assert(data);
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && data[child + 1] < data[child])
		{
			child++;
		}

		if (data[child] < data[parent])
		{
			Swap(&data[child], &data[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
	
}

void HeapPop(Heap* php)
{
	assert(!HeapEmpty(php));
	assert(php);
	Swap(&php->data[0], &php->data[php->size-1]);
	php->size--;

	AdjustDown(php->data, php->size, 0);
}

int HeapSize(Heap* php)
{
	assert(php);
	return php->size;
}

HeapDataType HeapTop(Heap* php)
{
	assert(php);
	return php->data[0];
}